<template>
  <div class="CyclePerform">
    <el-dialog
      custom-class="el-dialog-redefine"
      v-bind="$attrs"
      title="任务操作配置"
      :visible.sync="dialogVisible"
      :show-close="showClose"
      @open="dialogOpen"
    >
      <div class="outside-border">
        <div class="data-area">
          <el-tabs class="el-tabs-redefine" v-model="editableTabsValue" type="border-card">
            <el-tab-pane label="可用周期" name="first">
              <div class="tab-custom-area">
                <div class="conditions-area">
                  <el-form
                    ref="cycleForm"
                    :model="cycleForm"
                    :rules="cycleFormRules"
                    size="mini"
                    label-width="100px"
                  >
                    <div class="radio-type">
                      <el-form-item
                        style="height: 28px; margin: 0;"
                        size="mini"
                        label-width="0px"
                        label
                        prop="executeType"
                      >
                        <el-radio :label="0" v-model="cycleForm.executeType">周期</el-radio>
                      </el-form-item>
                    </div>
                    <el-form-item v-show="false" size="mini" label="任务Id:" prop="taskId">
                      <el-input size="mini" v-model="cycleForm.taskId" maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item v-show="false" size="mini" label="机器人Id:" prop="robotId">
                      <el-input size="mini" v-model="cycleForm.robotId" maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item v-show="false" size="mini" label="名称:" prop="name">
                      <el-input size="mini" v-model="cycleForm.name" maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item size="mini" label="月:" prop="month">
                      <el-checkbox-group
                        v-model="cycleForm.month"
                        :disabled="cycleForm.executeType === 1"
                      >
                        <el-checkbox label="1" name="type">一月</el-checkbox>
                        <el-checkbox label="2" name="type">二月</el-checkbox>
                        <el-checkbox label="3" name="type">三月</el-checkbox>
                        <el-checkbox label="4" name="type">四月</el-checkbox>
                        <el-checkbox label="5" name="type">五月</el-checkbox>
                        <el-checkbox label="6" name="type">六月</el-checkbox>
                        <el-checkbox label="7" name="type">七月</el-checkbox>
                        <el-checkbox label="8" name="type">八月</el-checkbox>
                        <el-checkbox label="9" name="type">九月</el-checkbox>
                        <el-checkbox label="10" name="type">十月</el-checkbox>
                        <el-checkbox label="11" name="type">十一月</el-checkbox>
                        <el-checkbox label="12" name="type">一二月</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                    <el-form-item size="mini" label="周:" prop="week">
                      <el-checkbox-group
                        v-model="cycleForm.week"
                        :disabled="cycleForm.executeType === 1"
                      >
                        <el-checkbox label="0" name="type">日</el-checkbox>
                        <el-checkbox label="1" name="type">一</el-checkbox>
                        <el-checkbox label="2" name="type">二</el-checkbox>
                        <el-checkbox label="3" name="type">三</el-checkbox>
                        <el-checkbox label="4" name="type">四</el-checkbox>
                        <el-checkbox label="5" name="type">五</el-checkbox>
                        <el-checkbox label="6" name="type">六</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                    <el-form-item size="mini" label="开始时间:" prop="executeTime">
                      <el-time-picker
                        size="mini"
                        v-model="cycleForm.executeTime"
                        value-format="HH:mm:ss"
                        format="HH:mm:ss"
                        placeholder="选择时间"
                        :disabled="cycleForm.executeType === 1"
                      ></el-time-picker>
                    </el-form-item>
                    <div class="radio-type">
                      <el-form-item
                        style="height: 28px; margin: 0;"
                        size="mini"
                        label-width="0px"
                        label
                        prop="executeType"
                      >
                        <el-radio :label="1" v-model="cycleForm.executeType">间隔</el-radio>
                      </el-form-item>
                    </div>
                    <el-row style="margin-top: 3px;">
                      <el-col style="width: 320px;">
                        <el-form-item size="mini" label="间隔时长:" prop="intervalTime">
                          <el-input
                            size="mini"
                            placeholder="请输入间隔时间"
                            v-model="cycleForm.intervalTime"
                            :disabled="cycleForm.executeType === 0"
                            maxlength="15"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col style="width: 80px">
                        <el-form-item size="mini" label-width="0px" label prop="intervalUnit">
                          <el-select
                            size="mini"
                            placeholder="请选择"
                            v-model="cycleForm.intervalUnit"
                            :disabled="cycleForm.executeType === 0"
                          >
                            <el-option
                              v-for="item in options"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- <el-form-item size="mini" label="开始时间:" prop="startTime">
                      <el-date-picker
                        size="mini"
                        type="datetime"
                        placeholder="选择日期时间"
                        v-model="cycleForm.startTime"
                        :picker-options="startPickerOptions"
                        :disabled="cycleForm.executeType === 0"
                        :picker-options="startPickerOptions"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item size="mini" label="结束时间:" prop="endTime">
                      <el-date-picker
                        size="mini"
                        type="datetime"
                        placeholder="选择日期时间"
                        v-model="cycleForm.endTime"
                        :picker-options="endPickerOptions"
                        :disabled="cycleForm.executeType === 0"
                      ></el-date-picker>
                    </el-form-item>-->
                    <el-form-item size="mini" label="结束时间:" prop="startTime">
                      <el-date-picker
                        size="mini"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        v-model="start_end_time"
                        @change="handleTimeChange"
                        :disabled="cycleForm.executeType === 0"
                        :picker-options="endPickerOptions"
                      ></el-date-picker>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="content-area">
                  <div class="config-operation">
                    <el-button class="but-empty" type="text" size="medium" @click="handleEmpty">
                      <i class="empty-icon"></i>清空
                    </el-button>
                    <el-button
                      class="but-save"
                      type="text"
                      size="medium"
                      :loading="saveLoading"
                      @click="handleSave"
                    >
                      <i class="save-icon"></i>保存
                    </el-button>
                    <el-button class="but-query" type="text" size="medium" @click="handleQuery">
                      <i class="query-icon"></i>汇总
                    </el-button>
                  </div>
                  <div class="config-list">
                    <el-table
                      :data="cycleData"
                      border
                      size="mini"
                      class="el-table-redefine"
                      style="width: 100%"
                      height="100%"
                    >
                      <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
                      <el-table-column prop="name" label="名称"></el-table-column>
                      <el-table-column prop="startTime" label="开始时间"></el-table-column>
                      <el-table-column prop="endTime" label="结束时间"></el-table-column>
                      <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                          <el-button
                            type="text"
                            size="mini"
                            @click="deleteRow(scope, scope.$index)"
                          >删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="禁用周期" name="second"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskCyclesList,
  taskCyclesAdd,
  taskCyclesDelete,
  robotParams,
  postOperationLogs
} from "@/api/apiManagement";
import { validatEmpty } from "@/utils/validate";

export default {
  name: "CyclePerform",
  props: {
    showClose: {
      type: Boolean,
      default: true
    },
    data: {
      type: [Array, Object],
      required: true
    }
  },
  data() {
    const endTimeValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 1) {
          callback(new Error("请选择结束时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const executeTimeValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 0) {
          callback(new Error("请选择执行时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const intervalTimeValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 1) {
          callback(new Error("请输入间隔时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const intervalUnitValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 1) {
          callback(new Error("请选择间隔单位"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const monthValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 0) {
          callback(new Error("请选择月"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const startTimeValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 1) {
          callback(new Error("请选择开始时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const weekValidate = (rule, value, callback) => {
      if (validatEmpty(value)) {
        if (this.cycleForm.executeType === 0) {
          callback(new Error("请选择周"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      robot_id: "",
      editableTabsValue: "first",
      options: [
        {
          value: 0,
          label: "分钟"
        },
        {
          value: 1,
          label: "小时"
        },
        {
          value: 2,
          label: "天"
        }
      ],
      start_end_time: "",
      cycleQueryForm: {
        page: 1,
        size: 0,
        taskId: null
      },
      saveLoading: false,
      cycleForm: {
        name: "",
        endTime: "",
        executeTime: "",
        executeType: 0,
        intervalTime: "",
        intervalUnit: 1,
        month: [],
        startTime: "",
        taskId: null,
        week: []
      },
      cycleFormRules: {
        name: [{ required: true, trigger: "blur", message: "请输入名字" }],
        endTime: [
          { required: true, trigger: "blur", validator: endTimeValidate }
        ],
        executeTime: [
          { required: true, trigger: "blur", validator: executeTimeValidate }
        ],
        executeType: [
          { required: true, trigger: "blur", message: "请选择执行类型" }
        ],
        intervalTime: [
          { required: true, trigger: "blur", validator: intervalTimeValidate }
        ],
        intervalUnit: [
          { required: true, trigger: "blur", validator: intervalUnitValidate }
        ],
        month: [{ required: true, trigger: "blur", validator: monthValidate }],
        startTime: [
          { required: true, trigger: "blur", validator: startTimeValidate }
        ],
        taskId: [{ required: true, trigger: "blur", message: "请输入任务Id" }],
        robotId: [
          { required: true, trigger: "blur", message: "请输入机器人Id" }
        ],
        week: [{ required: true, trigger: "blur", validator: weekValidate }]
      },
      cycleData: [],
      startPickerOptions: {
        disabledDate: time => {
          let endTime =
            this.cycleForm.endTime === null ? "" : this.cycleForm.endTime;
          return (
            time.getTime() > new Date(endTime).getTime() ||
            time.getTime() < Date.now() - 8.64e7
          );
        }
      },
      endPickerOptions: {
        disabledDate: time => {
          let startTime =
            this.cycleForm.startTime === null ? "" : this.cycleForm.startTime;
          return (
            time.getTime() < new Date(startTime).getTime() - 8.64e7 ||
            time.getTime() < Date.now() - 8.64e7
          );
        }
      },
      rosObj: {
        ip: "",
        port: ""
      }
    };
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {
    isShowDia(isVisible) {
      let self = this;
      self.dialogVisible = isVisible;
    },
    dialogOpen() {
      this.robot_id = localStorage.getItem("ydRobot_id");
      this.getRobotParams({
        page: 1,
        size: 0,
        robotId: this.robot_id,
        type: 3
      });
      this.cycleQueryForm.taskId = this.data.id;
      this.cycleForm.taskId = this.data.id;
      this.cycleForm.robotId = this.data.robotId;
      if (this.cycleQueryForm && this.cycleQueryForm.taskId) {
        this.getTaskCyclesList();
      }
    },
    handleEmpty() {
      this.start_end_time = null;
      this.cycleForm = {
        name: "",
        endTime: "",
        executeTime: "",
        executeType: 0,
        intervalTime: "",
        intervalUnit: 1,
        month: [],
        startTime: "",
        taskId: this.data.id,
        robotId: this.data.robotId,
        week: []
      };
    },
    handleTimeChange(value) {
      if (value) {
        this.cycleForm.startTime = value[0];
        this.cycleForm.endTime = value[1];
      } else {
        this.cycleForm.startTime = "";
        this.cycleForm.endTime = "";
      }
    },
    handleSave() {
      if (this.cycleForm && this.cycleForm.taskId && this.cycleForm.robotId) {
        if (this.cycleForm.executeType === 0) {
          this.cycleForm.month.sort();
          this.cycleForm.week.sort();
          var yearStr = "每年,";
          var monthStr = "";
          var weekStr = "";
          if (this.cycleForm.month.length >= 12) {
            monthStr = "每月,";
          } else {
            monthStr = "每" + this.cycleForm.month.join(",") + "月,";
          }
          if (this.cycleForm.week.length >= 7) {
            weekStr = "每天,";
          } else {
            weekStr = "每周" + this.cycleForm.week.join(",") + "每天,";
          }
          this.cycleForm.name =
            yearStr +
            monthStr +
            weekStr +
            this.cycleForm.executeTime +
            "执行一次";
        }
        if (this.cycleForm.executeType === 1) {
          var intervalTimeStr = this.cycleForm.intervalTime;
          var intervalUnitStr = "";
          this.options.map(item => {
            if (item.value === this.cycleForm.intervalUnit) {
              intervalUnitStr = item.label;
            }
          });
          this.cycleForm.name =
            "每间隔" + intervalTimeStr + intervalUnitStr + "执行一次";
        }
        this.$refs["cycleForm"].validate(valid => {
          if (valid) {
            this.saveLoading = !this.saveLoading;
            taskCyclesAdd({
              name: this.cycleForm.name,
              endTime: this.cycleForm.endTime,
              executeTime: this.cycleForm.executeTime,
              executeType: this.cycleForm.executeType,
              intervalTime: this.cycleForm.intervalTime,
              intervalUnit: this.cycleForm.intervalUnit,
              month: this.cycleForm.month.join(","),
              startTime: this.cycleForm.startTime,
              taskId: this.cycleForm.taskId,
              robotId: this.cycleForm.robotId,
              week: this.cycleForm.week.join(",")
            })
              .then(response => {
                this.setOperationLogs(
                  "配置-" + this.data.name + "的周期任务策略"
                );
                this.dbTableUpdatePub({
                  table_id: 5
                });
                this.handleEmpty();
                this.getTaskCyclesList();
                this.saveLoading = !this.saveLoading;
                this.$alert("保存成功", "提示", {
                  confirmButtonText: "确定",
                  callback: action => {
                    //
                  }
                });
              })
              .catch(() => {
                this.saveLoading = !this.saveLoading;
              });
          }
        });
      }
    },
    handleQuery() {},
    deleteRow(data, index) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (data.row && data.row.id) {
            taskCyclesDelete({}, data.row.id)
              .then(response => {
                this.setOperationLogs(
                  "删除-" + this.data.name + "的周期任务策略"
                );
                this.dbTableUpdatePub({
                  table_id: 5
                });
                this.getTaskCyclesList();
                this.$message({
                  message: "删除成功!",
                  type: "success"
                });
              })
              .catch(() => {});
          } else {
            this.cycleData.splice(index, 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    getTaskCyclesList() {
      taskCyclesList(this.cycleQueryForm)
        .then(response => {
          if (response.list) {
            this.cycleData = response.list;
          }
        })
        .catch(() => {});
    },
    getRobotParams(data) {
      robotParams(data)
        .then(response => {
          if (response.list && response.list.length > 0) {
            for (var i = 0, len = response.list.length; i < len; i++) {
              if (response.list[i].name === "ros_websocket_ip") {
                this.rosObj.ip = response.list[i].value;
              }
              if (response.list[i].name === "ros_websocket_port") {
                this.rosObj.port = response.list[i].value;
              }
            }
          }
        })
        .catch(() => {});
    },
    // 添加日志管理
    setOperationLogs(content) {
      var parm = {
        content: content,
        deviceId: localStorage.getItem("ydRobot_device_id"),
        type: 0
      };
      postOperationLogs(parm)
        .then(response => {})
        .catch(() => {});
    }
  }
};
</script>

<style>
.CyclePerform {
  /*  */
}
.CyclePerform .el-dialog-redefine {
  width: 70%;
  height: 80%;
  margin-top: 8vh !important;
  min-height: 600px;
}
.CyclePerform .el-dialog__header {
  padding: 0;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}
.CyclePerform .el-dialog__header .el-dialog__title {
  line-height: 27px;
  font-size: 14px;
  color: #202123;
  padding: 0 6px;
}
.CyclePerform .el-dialog__header .el-dialog__headerbtn {
  width: 23px;
  height: 23px;
  top: 2px;
  right: 5px;
  font-size: 18px;
  border-radius: 3px;
  border: 1px solid rgb(177, 211, 162);
}
.CyclePerform .el-dialog__body {
  height: calc(100% - 27px);
  padding: 3px;
  background-color: rgb(227, 242, 238);
}
.CyclePerform .outside-border {
  width: 100%;
  height: 100%;
  padding: 6px 8px;
  border: 1px solid rgb(194, 221, 228);
  background-color: #ffffff;
}
.CyclePerform .data-area {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid rgb(202, 231, 238);
}

.CyclePerform .el-tabs-redefine {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}

.CyclePerform .el-tabs__header {
  box-sizing: border-box;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}

.CyclePerform .el-tabs--border-card {
  border: none;
}

.CyclePerform .el-tabs--border-card > .el-tabs__content {
  flex-grow: 1;
  padding: 8px 8px 8px 8px;
}

.CyclePerform .el-tabs--border-card > .el-tabs__header .el-tabs__item {
  height: 30px;
  margin: 0px 3px 0px 3px;
  line-height: 30px;
  border: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  color: #000;
}

.CyclePerform
  .el-tabs--border-card
  > .el-tabs__header
  .el-tabs__item.is-active {
  color: rgb(16, 156, 180);
  border: 1px solid rgb(16, 156, 180);
  border-bottom: none;
}

.CyclePerform .el-tab-pane {
  width: 100%;
  height: 100%;
}

.CyclePerform .tab-custom-area {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}

.CyclePerform .conditions-area {
  width: 100%;
  height: auto;
  border: 1px solid rgb(186, 232, 247);
}
.CyclePerform .el-form-item--mini.el-form-item {
  margin-top: 0;
  margin-bottom: 14px;
}
.CyclePerform .radio-type {
  width: 100%;
  height: 28px;
  padding: 0 8px;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}
.CyclePerform .el-checkbox-group {
  height: 28px;
}
.CyclePerform .el-checkbox {
  margin-right: 10px;
}
.CyclePerform .el-checkbox .el-checkbox__label {
  padding-left: 5px;
}
.CyclePerform .content-area {
  position: relative;
  width: 100%;
  /* height: auto; */
  margin-top: 8px;
  border: 1px solid rgb(186, 232, 247);
  flex-grow: 1;
}
.CyclePerform .config-operation {
  width: 100%;
  height: 30px;
  background-color: #efefef;
  border-bottom: 1px solid #e1e1e1;
}
.CyclePerform .but-empty,
.CyclePerform .but-save,
.CyclePerform .but-query {
  height: 27px;
  margin-left: 15px;
  margin-right: 10px;
  padding: 0;
  font-size: 13px;
  color: #000;
  float: left;
}
.CyclePerform .empty-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../../static/resources/images/remove.png);
  background-size: 100% 100%;
  float: left;
}
.CyclePerform .save-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../../static/resources/images/save.png);
  background-size: 100% 100%;
  float: left;
}
.CyclePerform .query-icon {
  width: 14px;
  height: 14px;
  margin-right: 3px;
  background-image: url(../../../../static/resources/images/query.png);
  background-size: 100% 100%;
  float: left;
}
.CyclePerform .config-list {
  position: absolute;
  width: 100%;
  height: calc(100% - 30px);
  /* overflow: auto; */
}
.CyclePerform .el-table-redefine {
  width: 100%;
  height: 100%;
  /* display: flex;
  flex-flow: column; */
}
.CyclePerform
  .el-table-redefine
  .el-table__header-wrapper
  .el-table__header
  .has-gutter
  th {
  background-color: #efefef;
  border-right: 1px solid #e1e1e1;
}
.CyclePerform .el-table-redefine .el-table__body-wrapper {
  /* overflow: hidden;
  overflow-y: auto;
  flex-grow: 1; */
}
</style>